import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';


///绘制图片 文本  添加水印
///http://wed.xjx100.cn/news/41178.html?action=onClick
class ImageUtils{

  //读取 assets 中的图片
  Future<ui.Image> loadImageFromAssets(String path) async {
    ByteData data = await rootBundle.load(path);
    Uint8List bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    return decodeImageFromList(bytes);
  }


  ///绘制图片信息  从下往上 一层一层绘制
  Future<Uint8List> createCanvas(String title,String text) async {
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);
    ///设置大小
    Size boxSize = const Size(220,200);
    // canvas.drawRect(ui.Offset.zero & boxSize, ui.Paint()..color = Colors.amberAccent);
    ui.Image _image = await loadImageFromAssets('assets/bg_paopao.png');

    // canvas.drawImage(
    //     _image, Offset(-_image.width / 2, -_image.height / 2), ui.Paint());

    canvas.drawImage(_image,const  Offset(20, 0), ui.Paint());

    // canvas.drawImageRect(_image, Rect.fromLTRB(0,0,0,0,), Rect.fromLTRB(0,0,0,0),  ui.Paint());


    ///绘制背景
    canvas.drawRect(ui.Offset.zero & boxSize, ui.Paint()..color = Colors.white);

    ///绘制文字信息
    TextPainter textPainter = TextPainter(
        text: TextSpan(
          children: [
            TextSpan(text: title,style:const TextStyle(fontSize: 30,fontWeight: ui.FontWeight.bold, color: Colors.black87)),
            const TextSpan(text: '\n\n',style: TextStyle(fontSize: 15)),
            TextSpan(text: text,style:const TextStyle(fontSize: 25,fontWeight: ui.FontWeight.bold, color: Colors.black38)),

          ],),
        textAlign: TextAlign.center,
        textDirection: TextDirection.ltr);
    textPainter.layout(); // 进行布局
    Size size = textPainter.size; // 尺寸必须在布局后获取

    textPainter.paint(canvas, Offset(size.width/2-30, size.height / 2-15));

    ui.Picture picture = recorder.endRecording();
    ui.Image image = await picture.toImage(boxSize.width.toInt(), boxSize.height.toInt());
    ByteData? byteData = await image.toByteData(format:  ui.ImageByteFormat.png);
    return byteData!.buffer.asUint8List();
  }

}